(function ($) {

    Backbone.sync = function(method, model, success, error){
        success();
    };

    //сквозной счетчик для присвоения айди
    var counter = 0;

    // модель виджета Текст
    var TxtWidgetModel = Backbone.Model.extend({
        defaults:{
            defText: '<h1>Default text ----- Text Widget</h1>'
        }
    });

    //коллекция моделей виджетов
    var TxtWidgetsCollection = Backbone.Collection.extend({
        model: TxtWidgetModel
    });

    //вьюха модели виджета Текст
    var TxtWidgetModelView = Backbone.View.extend({
        tagName: 'div',
        className: 'txt-widget-wrap',

        events: {
            'click .delete': 'delTxtWidget'
        },

        initialize: function(){
            _.bindAll(this, 'render', 'delTxtWidget');
        },

        render: function(){
            $(this.el).html('<div class="txt-widget-content" id="txt-widget-content-id' + counter + '" contenteditable="true">'+this.model.get('defText')+'</div><p class="drag">Drag me</p><p class="delete">Delete me</p>');
            $(this.el).attr("id", "txt-widget-wrap-id" + counter + "");
            $(this.el).draggable({ handle: ".drag" }, { grid: [ 5,5 ] }, { containment: "#change-content" });
            $('.txt-widget-content', this.el).each(function(){
                CKEDITOR.disableAutoInline = true;
                CKEDITOR.inline( this );
            });

            return this;
        },

        delTxtWidget: function(){
            $(this.el).remove();
            this.model.destroy();
        }
    });

    // Вьюха приложения (конструктор/основной контент страницы)
    var PageView = Backbone.View.extend({
        el: $('#change-content'),

        events: {
            'click #add-txt-widget': 'addTxtWidget',
            'click #show-collection': 'showCollection'
        },

        initialize: function() {
            _.bindAll(this, 'render', 'addTxtWidget', 'appendTxtWidgetView', 'showCollection');

            this.collection = new TxtWidgetsCollection();
            this.collection.bind('add', this.appendTxtWidgetView);

            this.render();
        },

        render: function(){
            var that = this;
            $(this.el).append('<div class="button-group minor-group" id="builder-panel"><a href="#" class="button" id="add-txt-widget">Add a Text Widget</a><a href="#" class="button" id="show-collection">Show a collection</a></div>');
            _(this.collection.models).each(function(txtWidgetModel) {
                that.appendTxtWidgetView(txtWidgetModel);
            }, this);
        },

        addTxtWidget: function(){
            counter++;
            var txtWidgetModel = new TxtWidgetModel();
            this.collection.add(txtWidgetModel);
        },

        appendTxtWidgetView: function(txtWidgetModel){
            var txtWidgetModelView = new TxtWidgetModelView({
                model: txtWidgetModel
            });
            $(this.el).append(txtWidgetModelView.render().el);
        },

        showCollection: function(){
            //console.log(this.collection.length);
            console.log(JSON.stringify(this.collection));
        }
    });

    var pageView = new PageView();

})(jQuery);
